<?php
namespace app\product\admin;
use app\system\admin\Admin;
use app\product\model\Supplier as SupplierModel;
use think\Db;
class Supplier extends Admin
{
    protected $hisiModel = 'Supplier';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function index()
    {
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $bill_id    = $this->request->param('bill_id','');
            $type       = $this->request->param('type',1);
            if ($bill_id) {
                $where['id'] = $bill_id;
            }
            if($type == 2){
                $data['data'] = SupplierModel::where($where)
                                // ->page($page)
                                // ->limit($limit)
                                ->order('id desc')
                                ->select();
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['total_recharge_amount'] = Db::name('supplier_money')->where('supplier_id', $value['id'])->where('out_in',1)->sum('price');
                    $data['data'][$key]['consumption_amount'] = Db::name('supplier_money')->where('supplier_id', $value['id'])->where('out_in',2)->sum('price');
                    $data['data'][$key]['balance'] = $data['data'][$key]['total_recharge_amount'] - $data['data'][$key]['consumption_amount'];
                }
                $data['count'] = SupplierModel::where($where)->count('id');
                $data['code'] = 0;
                return json($data);
            }else{
                $data['data'] = SupplierModel::where($where)
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['total_recharge_amount'] = Db::name('supplier_money')->where('supplier_id', $value['id'])->where('out_in',1)->sum('price');
                    $data['data'][$key]['consumption_amount'] = Db::name('supplier_money')->where('supplier_id', $value['id'])->where('out_in',2)->sum('price');
                    $data['data'][$key]['balance'] = $data['data'][$key]['total_recharge_amount'] - $data['data'][$key]['consumption_amount'];
                }
                $data['count'] = SupplierModel::where($where)->count('id');
                $data['code'] = 0;
                return json($data);
            }


        }
        $bills = Db::name('supplier')->field('id,name')->all();
        $this->assign('bills',$bills);
        $this->assign('hisiTabType', 0);
        $this->assign('hisiTabData', '');
        return $this->fetch();
    }
}
